//中间件层
const bcrypt = require("bcryptjs");
const { getUserInfo } = require("../service/user.service");
const {
    userFormateError,
    userAlreadyExited,
    userRegisterError,
    userDoesNotExist,
    userLoginError,
    invalidPassword,
} = require("../constant/err.type");

const userValidator = async (ctx, next) => {
    const { user_name, password } = ctx.request.body;
    //合法性
    if (!user_name || !password) {
        //定位错误
        console.error("用户名或密码为空", ctx.request.body);
        //触发error事件，传递参数（err, ctx）给事件处理程序，之后app.on('error',)处理事件
        ctx.app.emit("error", userFormateError, ctx);
        return;
    }
    await next();
};

const verifyUser = async (ctx, next) => {
    const { user_name } = ctx.request.body;
    //合理性 用户存在就跳过  必须加await，不然返回一个promise对象永远都是true
    try {
        if (await getUserInfo({ user_name })) {
            console.error("用户名已存在", ctx.request.body);
            ctx.app.emit("error", userAlreadyExited, ctx);
            return;
        }
    } catch (error) {
        console.error("获取用户信息错误", error);
        ctx.app.emit("error", userRegisterError, ctx);
        return;
    }

    await next();
};

//加密
const crpytPassword = async (ctx, next) => {
    const { password } = ctx.request.body;

    const salt = bcrypt.genSaltSync(10); //加盐十次
    const hash = bcrypt.hashSync(password, salt); //加密

    ctx.request.body.password = hash;
    await next();
};

const verifyLogin = async (ctx, next) => {
    const { user_name, password } = ctx.request.body;
    
    try {
        //判断用户是否存在
        const res = await getUserInfo({ user_name })
        if (!res) {
            console.error("用户不存在", { user_name });
            ctx.app.emit("error", userDoesNotExist, ctx);
            return;
        }

        //密码是否匹配
        if(!bcrypt.compareSync(password, res.password)){
            ctx.app.emit("error", invalidPassword, ctx);
            return
        }
    } catch (error) {
        console.log(error);
        ctx.app.emit("error", userLoginError, ctx);
        return
    }

    await next()
};

module.exports = {
    userValidator,
    verifyUser,
    crpytPassword,
    verifyLogin,
};
